<template>
  <div class="container" ref="container">
    <img src="@/assets/images/8000.jpg" alt="" srcset="" />
    <!-- <img src="@/assets/images/8005.jpg" alt="" srcset="" />  -->
  </div>
</template>

<script setup>
import { gsap } from "gsap-trial";
import { onMounted, ref, reactive, computed, watch } from "vue";
const container = ref();
const loadCanvas = (id) => {
  const canvas = document.createElement("canvas");
  canvas.width = 80;
  canvas.height = 80;
  canvas.id = id;
  canvas.className = "block";
  // canvas.style.opacity = 0; // 初始化透明度为0
  container.value.appendChild(canvas);
};
const loadImg = (curCanvasId, i, j) => {
  const img = new Image();
  img.src = require(`../assets/images/8005.jpg`);
  img.onload = () => {
    const ctx = document.getElementById(curCanvasId).getContext("2d");
    let sX = j * 80;
    let sY = i * 80;
    let sW = 80;
    let sH = 80;
    let dX = 0;
    let dY = 0;
    let dW = sW;
    let dH = sH;
    ctx.drawImage(img, sX, sY, sW, sH, dX, dY, dW, dH);
  };
};

const collectionAnimation = () => {
  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      const curCanvasId = `canvas_column-${i}${j}`;
      loadCanvas(curCanvasId);
      loadImg(curCanvasId, i, j);
    }
  }
};

const startAnimagtion = () => {
  let tl = gsap.timeline();
  let angle = ref(0);
  let click = ref(1);
  document.addEventListener("click", () => {
    angle.value += 360;

    // demo1
    // tl.to(".block", {
    //   opacity: 1, // 透明度从0变为1
    //   duration: 2,
    //   rotateZ: angle.value,
    //   // x: window.innerWidth,
    //   ease: "back.inOut(6)",
    //   stagger: {
    //     grid: [10, 10],
    //     from: "center",
    //     // amount: 0.5, // 动画之间的延迟时间
    //   },
    // });

    // demo2
    if (click.value === 1) {
      click.value = 2;
      tl.to(".block", {
        duration: 2.5,
        rotateZ: angle.value,
        x: 800,
        ease: "back.inOut(6)",
        stagger: {
          amount: 2.5,
          grid: "auto",
          from: "end",
        },
      });
    } else if (click.value === 2) {
      click.value = 1;
      tl.to(".block", {
        duration: 2.5,
        rotateZ: angle.value,
        x: 0,
        ease: "back.inOut(7)",
        stagger: {
          amount: 1.5,
          grid: "auto",
          from: "center",
        },
      });
    }
  });
};
onMounted(() => {
  collectionAnimation();
  startAnimagtion();
});
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  display: flex;
  flex-flow: row wrap;
}
img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  // opacity: 0.7;
}
canvas {
  position: relative;
  width: 10%;
  height: 10%;
  display: inline-block;
}
</style>
